<template>
  <div class="mod-mp__account">
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
      <el-form-item>
        <el-input v-model="state.dataForm.name" placeholder="名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.accountName" placeholder="账号名" clearable></el-input>
      </el-form-item>
      <el-form-item prop="status">
        <ren-select v-model="state.dataForm.status" dict-type="wx_articles_status" placeholder="状态"></ren-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="state.getDataList()">{{ $t("query") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle()">{{ $t("add") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="syncHandle()" :loading="loading">同步草稿</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="state.deleteHandle()">{{ $t("deleteBatch") }}</el-button>
      </el-form-item>
    </el-form>
    <el-table size="small" v-loading="state.dataListLoading" :data="state.dataList" border @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="coverUrl" label="文章源" header-align="center" align="center">
        <template v-slot="scope">
          <el-link type="primary">{{ scope.row.origTitle }}</el-link>
          <el-link type="primary" :href="scope.row.origUrl" target="_blank">{{ scope.row.origUrl ? scope.row.origUrl.substring(0, 20) : "-" }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="新标题" header-align="center" align="center">
        <template v-slot="scope">
          <el-popover placement="right" :width="400" trigger="click" @show="titleShowHandle(scope.row)">
            <template #reference>
              <div>
                <el-link type="success">{{ scope.row.title }}</el-link>
                <el-icon size="20">
                  <Edit />
                </el-icon>
              </div>
            </template>
            <el-radio-group v-model="scope.row.title" @change="titleChangeHandle($event, scope.row)">
              <el-radio :label="item" v-for="(item, index) in scope.row.titles" :key="index">{{ item }}</el-radio>
            </el-radio-group>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="accountName" label="账号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="coverUrl" label="文章封面" header-align="center" align="center">
        <template v-slot="scope">
          <el-link type="danger" @click="coverAddOrUpdateHandle(scope.row.id)" v-if="!scope.row.coverUrl">点击设置</el-link>
          <el-link type="primary" @click="coverAddOrUpdateHandle(scope.row.id)" v-else>已设置</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" header-align="center" align="center">
        <template v-slot="scope">
          <dict-label dict-type="wx_articles_status" :dict-value="scope.row.status" :status="{ 0: 'warning', 2: 'info', 5: 'success', 6: 'success', 7: 'danger' }"></dict-label>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" header-align="center" align="center"></el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="140">
        <template v-slot="scope">
          <el-button type="primary" link @click="previewHandle(scope.row)">预览</el-button>
          <el-button type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-popconfirm title="确认是否同步到微信平台? 确认：1信息无误，2封面已设置" @confirm="syncHandle(scope.row)">
            <template #reference>
              <el-button type="primary" :loading="loading" v-if="scope.row.status === 2" link>同步草稿</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确认是否发布到微信平台?" @confirm="sendHandle(scope.row)">
            <template #reference>
              <el-button type="danger" v-if="scope.row.status === 5" link :loading="loading">发布</el-button>
            </template>
          </el-popconfirm>
          <!-- <el-button type="primary" link @click="mpHandle(scope.row.appId)">接入</el-button> -->
          <el-button type="primary" link @click="state.deleteHandle(scope.row.id)">{{ $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="Tips" width="500">
      <div class="preview-container" v-html="previewHtml"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="15" :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update ref="addOrUpdateRef" @refreshDataList="state.getDataList"></add-or-update>
    <cover-add-or-update ref="coverAddOrUpdateRef" @refreshDataList="state.getDataList"></cover-add-or-update>
  </div>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs } from "vue";
import AddOrUpdate from "./draft-add-or-update.vue";
import CoverAddOrUpdate from "./draft-cover-add-or-update.vue";
import app from "@/constants/app";
import baseService from "@/service/baseService";
import { Edit } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const view = reactive({
  getDataListURL: "/wechat/publicarticles/page",
  getDataListIsPage: true,
  deleteURL: "/wechat/publicarticles",
  deleteIsBatch: true,
  dataForm: {
    name: "",
    status: "",
    accountId: "",
    accountName: ""
  }
});

let loading = ref(false);

const state = reactive({ ...useView(view), ...toRefs(view) });

const mpHandle = (appId: any) => {
  ElMessageBox.alert(app.api + "/mp/portal/" + appId, "公众号配置的URL", {
    confirmButtonText: t("confirm")
  });
};

const splitAndCleanData = (data: any) => {
  // 先按照 &split; 进行拆分
  let splitData = data.split("&split;");

  // 遍历拆分后的数组，去除每个元素中的 \ 和引号
  for (let i = 0; i < splitData.length; i++) {
    splitData[i] = splitData[i].replace(/\\/g, "").replace(/"/g, "");
  }

  return splitData;
};

const titleShowHandle = (row?: any) => {
  if (row.titleExt) {
    row.titles = splitAndCleanData(row.titleExt);
  }
};

const titleChangeHandle = (event: any, value: any) => {
  baseService.put("/wechat/publicarticles", { id: value.id, title: event });
};

let dialogVisible = ref(false);
let previewHtml = ref("");

const previewHandle = (value: any) => {
  dialogVisible.value = true;
  previewHtml.value = value.content;
};

const syncHandle = (row?: any) => {
  let accountId = "";
  let articleIdList = [];
  if (row) {
    accountId = row.accountId;
    articleIdList = [row.id];
  } else if (!row && state.dataListSelections?.length) {
    articleIdList = state.dataListSelections.map((item) => item.id);
    accountId = state.dataListSelections[0]["accountId"];
  }
  const dataForm = {
    accountId,
    articleIdList
  };
  loading.value = true;
  baseService
    .put("/wechat/publicarticles/sync_article", dataForm)
    .then((res) => {
      loading.value = false;
      state.getDataList();
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

const sendHandle = (row: any) => {
  const dataForm = {
    articleId: row.id
  };
  loading.value = true;
  baseService
    .put("/wechat/publicarticles/publish", dataForm)
    .then(() => {
      loading.value = false;
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
  addOrUpdateRef.value.init(id);
};

const coverAddOrUpdateRef = ref();
const coverAddOrUpdateHandle = (id?: number) => {
  coverAddOrUpdateRef.value.init(id);
};
</script>
